﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Text;
using System.Collections.Generic;

using Groupware;
namespace TripLOA.GUI
{
	public partial class messages : TripLOA.GUI.internationalization.LOABasePage
	{
		Security.TripLoaUser user;

        private bool GridViewInBox
		{
			get
			{
				if (ViewState["box"] == null)
					ViewState["box"] = true; ;
				return (bool)ViewState["box"];
			}
			set { ViewState["box"] = value; }
		}

        private List<Message> GridViewBox
		{
			get
			{
				if (ViewState["GridViewBox"] == null)
					ViewState["GridViewBox"] = MessageManager.RetrieveUserReceivedMessages(user);

				return (List<Message>)ViewState["GridViewBox"];
			}
			set { ViewState["GridViewBox"] = value; }
		}

		protected void Page_Load(object sender, EventArgs e)
		{

			user = Security.TripLoaUserManager.Instance.getUser(User.Identity.Name);
            addAutoComplete();
		  
	
			if (!Page.IsPostBack)
			{
				//Get Messages Unread
				Btn_NewMessages.Text += "(" + MessageManager.GetUserUnreadMessageCount(user) + ")";
				SetDataBind();

				LinkButtonSendReply.Visible = false;
                DivViewTextPM.Visible = false;
                DivMessages.Style.Add("display", "none");
			}

        }
       
        /// <summary>
        /// associate autocompletamento based on the list
        /// of friends to textbox for insert of the sender
        /// </summary>
        private void addAutoComplete()
        {
            ClientScriptManager cs = Page.ClientScript;
            String csname1 = "ScriptAutocomplete";
            Type cstype = this.GetType();
            String cstext1 = "$(document).ready(function(){$(\"#ctl00_ContentHomePage_TextBoxInsertDest\").autocompleteArray([";
            List<Security.Profile> friendList = user.GetProfile().BuddyList;
            // Check to see if the startup script is already registered.
            if (!cs.IsStartupScriptRegistered(cstype, csname1))
            {
                for(int i = 0 ;i < friendList.Count; i++){
                      cstext1+="\""+friendList.ElementAt(i).Username;
                      cstext1 += (i == friendList.Count - 1) ? "\"" : "\",";
                    }      
                cstext1 += "]); });   ";
                cs.RegisterStartupScript(cstype, csname1, cstext1, true);
            }
        }

        #region Set DataBind and DataSource to the GridView
        /// <summary>
        /// Binds the data source to the GridView control
        /// </summary>
		private void SetDataBind()
		{
			SetDataSource();
			GridViewMessages.DataBind();
		}
        /// <summary>
        /// set the datasource to the GridView and save in ViewState
        /// </summary>
		private void SetDataSource()
		{
			if (GridViewInBox)
			{// received messages
				GridViewBox = MessageManager.RetrieveUserReceivedMessages(user);
				GridViewMessages.Columns[0].Visible = false;
				GridViewMessages.Columns[1].Visible = true;
			}
			else
			{         // sented messages  
				GridViewBox = MessageManager.RetrieveUserSentMessages(user);
				GridViewMessages.Columns[0].Visible = true;
				GridViewMessages.Columns[1].Visible = false;
			}
			GridViewMessages.DataSource = GridViewBox;
        }
        #endregion

        #region Handling Events of the GridView
        /// <summary>
        /// When any of these rows are created, the GridView control fires a RowCreated event, 
        /// for which you can respond to with an appropriate handler.
        /// </summary>
        /// <param name="sender">his is the object which did fire the event</param>
        /// <param name="e">Additional information on the row created</param>
        protected void GridViewMessages_RowCreated(object sender, GridViewRowEventArgs e)
		{
            Message m = (Message)e.Row.DataItem;
			if (m != null)
            {
                GridViewRow row = e.Row;
                Image img = (Image)row.FindControl("Image_NewMess");
                if (!m.IsRead)
                {
                    img.ImageUrl = "../master/resourcesNew/img/mess.jpg";
              
                    img.Visible = true;
                }
                 img = (Image)row.FindControl("Image_Priority");
                if (m.Priority)
                {
                    img.ImageUrl = "../master/resourcesNew/img/priority.jpg";

                    img.Visible = true;
                }
            }
		  
		}
        /// <summary>
        /// The RowCommand event is raised whenever any button associated with a row in the GridView is clicked. This provides 
        /// for programmatically determining which specific command button is clicked and take appropriate action.
        /// </summary>
        /// <param name="sender">his is the object which did fire the event</param>
        /// <param name="e">
        /// Information related to the RowCommand event is passed via a GridViewCommandEventArgs 
        /// object to the method assigned to handle the event. The following GridViewCommandEventArgs properties provide 
        /// information specific to this event.
        /// </param>
		protected void GridViewMessages_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
		{
			if (e.CommandName == "GoToProperties")
			{
	
				// Retrieve the row index stored in the 
				// CommandArgument property.
				int index = Convert.ToInt32(e.CommandArgument);
				int rowidx = GridViewMessages.PageSize * GridViewMessages.PageIndex;

				Message m = GridViewBox.ElementAt((rowidx) + index);

			
				Label_SubjTitle.Text = GetLocalResourceObject("BoundFieldResource2.HeaderText").ToString() + " : ";
				Label_Subj.Text = m.Title;
				TextBoxViewTextPM.Text = m.Text;


				if (!GridViewInBox)
				{
					LinkButtonReply.Visible = false;
					Label_NickTitle.Text = GridViewMessages.HeaderRow.Cells[0].Text + " : ";
					Label_Nick.Text = "";
					for (int i = 0; i < m.Receiver.Count; i++)
					{
						Label_Nick.Text += m.Receiver.ElementAt(i)+"; ";
					}
                    LinkButtonSendReply.Visible = false;
                    LinkButtonReply.Visible = false;
				}
				else
				{
					Label_NickTitle.Text = GridViewMessages.HeaderRow.Cells[1].Text + " : ";
					Label_Nick.Text = m.Sender;
                    LinkButtonSendReply.Visible = false;
                    LinkButtonReply.Visible = true;
				}

                TextBoxViewTextPM.Visible = false;
                DivViewTextPM.Visible = true;

                DivMessages.Style.Remove("display");
            
                setHtmlText(m.Text);  
               
				if (!m.IsRead)				
					m.MarkAsRead(user);

                SetDataBind();

			}

		}
        /// <summary>
        /// formatting the message with the break and insert the text in the 
        /// field hidden textMessPreSmile
        /// </summary>
        /// <param name="text">text to format </param>
        private  void setHtmlText(String text)
        {
      
            int i = 0;
            textMessPreSmile.Value = "";
            while (i < text.Length && i != -1)
            {
                int idx = text.IndexOf("\r\n", i);
                if (idx != -1)
                {


                    textMessPreSmile.Value += text.Substring(i, (idx - i));
                    textMessPreSmile.Value += "(breakbrspace)";
                    idx++;
                }
                else
                    textMessPreSmile.Value += text.Substring(i);
                i = idx;
            }


        }

        /// <summary>
        /// event is raised whenever any of the buttons in the page selection element of a GridView
        /// control is clicked, but before the GridView handles the paging
        /// </summary>
        /// <param name="sender">his is the object which did fire the event<</param>
        /// <param name="e">object containing data related to this event</param>
		protected void GridViewMessages_PageIndexChanging(Object sender, GridViewPageEventArgs e)
		{
			if (GridViewMessages.EditIndex != -1)
				e.Cancel = true;
			else
			{
				SetDataSource();
				int pageIndex = e.NewPageIndex;
				GridViewMessages.PageIndex = pageIndex;
				GridViewMessages.DataBind();
			}

            DivMessages.Style.Add("display", "none");
        }



        #endregion

        #region Handling Events of the DropDownList
        /// <summary>
        /// allows you to select the Inbox or Outbox
        /// </summary>
        /// <param name="sender">his is the object which did fire the event</param>
        /// <param name="e">is an object to additional info</param>
        protected void MailMode_SelectedIndexChanged(object sender, EventArgs e)
		{
		 
			if (GridViewInBox)// set GridView in SentMessages Mode    
				GridViewInBox = false;
			else if (!GridViewInBox)// set GridView in ReceivedMessages Mode 
				GridViewInBox = true;
			SetDataBind();
        }
        /// <summary>	
        /// allows you to change the  page size  of the gridview
        /// </summary>
        /// <param name="sender">his is the object which did fire the event</param>
        /// <param name="e">is an object to additional info</param>
		protected void DropDownListPageSize_SelectedIndexChanged(object sender, EventArgs e)
		{
			SetDataSource();
			int pageSize = Convert.ToInt32(DropDownListPageSize.SelectedItem.Text);
			GridViewMessages.PageSize = pageSize;
			GridViewMessages.DataBind();
        }
        #endregion

        #region Handling Events Buttons's OnClick
        /// <summary>
        /// Event Handler 'button click' on the button 'Send'
        /// </summary>
        /// <param name="sender">his is the object which did fire the event</param>
        /// <param name="e">is an object to additional info</param>
		protected void ButtonSend_Click(object sender, EventArgs e)
		{
			bool priority = CheckBoxPriority.Checked;
            String myNick = user.UserName;
			String textSubject = TextBox_Subject.Text;
			if (textSubject.Trim().Equals(""))
				textSubject = "[click]";
            SendReport errorSend = null;
			List<string> otherNick = new List<string>();
			TextBoxTextMess.Text.Replace("\n", "\n\r");
			Message sendMess = new Message { Title = textSubject, Text = TextBoxTextMess.Text, Priority = priority };
            if (myNick.Equals(TextBoxInsertDest.Text))
            {
                ReportSend(errorSend, true); return;
            }

            if (TextBoxOtherNick.Text.Trim().Equals(""))
            {

              errorSend = sendMess.Send(user, TextBoxInsertDest.Text);
            }
            else
            {
            
                    otherNick.Add(TextBoxInsertDest.Text);
           
                char[] delims = ";".ToCharArray();
                string[] tokens = TextBoxOtherNick.Text.Split(delims);
                foreach (string token in tokens)
                {
                    if (token.Length == 0) continue;
                    if (!myNick.Equals(token) && !TextBoxInsertDest.Text.Equals(token))
                        otherNick.Add(token);
                }
            errorSend = sendMess.Send(user, otherNick);

            }

			ReportSend(errorSend,false);
			SetDataBind();

		}
       
        /// <summary>
        ///  Show warning after the method "send()"
        /// </summary>
        /// <param name="errorSend">ReportSend after the method Send</param>
        /// <param name="yourself">if I sent the message to myself</param>
        private void ReportSend(SendReport errorSend, bool yourself)
		{


			ClientScriptManager cs = Page.ClientScript;
			String csname1 = "PopupScript";
			Type cstype = this.GetType();
			String statusMess = null;

            if (yourself)
            statusMess = GetLocalResourceObject("StatusSendMessErrorYourself").ToString();
            else if (errorSend == null)
			{
				statusMess = GetLocalResourceObject("StatusSendMessErrorServer").ToString();
			}
			else if (errorSend.Succeded)
			{
				statusMess = GetLocalResourceObject("StatusSendMessOk").ToString();
				TextBoxInsertDest.Text = "";
				TextBoxOtherNick.Text = "";
				TextBox_Subject.Text = "";
				TextBoxTextMess.Text = "";
				CheckBoxPriority.Checked = false;

			}
			else
			{ //set nick not found
				statusMess = GetLocalResourceObject("StatusSendMessError").ToString() + " ";
				for (int i = 0; i < errorSend.NonexistentRecipients.Count; i++)
                    statusMess += errorSend.NonexistentRecipients.ElementAt(i) + ";  ";
			}

			// Check to see if the startup script is already registered.
			if (!cs.IsStartupScriptRegistered(cstype, csname1))
			{
                String cstext1 = "  $('div.DivViewPM').hide();alert('" + statusMess + "');";
				cs.RegisterStartupScript(cstype, csname1, cstext1, true);

			}

		}
        /// <summary>
        /// Event Handler 'button click' on the button 'Inbox'
        /// </summary>
        /// <param name="sender">his is the object which did fire the event</param>
        /// <param name="e">is an object to additional info</param>
		protected void Btn_NewMessages_Click(object sender, EventArgs e)
		{
		  
			DropDownListMailMode.SelectedIndex = 0;
			GridViewInBox = true;
			SetDataBind();
		}
        /// <summary>
        /// Event Handler 'button click' on the button 'close'
        /// </summary>
        /// <param name="sender">his is the object which did fire the event</param>
        /// <param name="e">is an object to additional info</param>
		protected void ButtonClose_Click(object sender, EventArgs e)
		{
     
			//DivMessages.Visible = false;
			LinkButtonReply.Visible = true;
            String js = "<script language='javascript'> closeDiv(); </script>";
            ClientScript.RegisterClientScriptBlock(this.GetType(), "closeDivMessage", js);
		}
        /// <summary>
        /// Event Handler 'button click' on the button 'delete'
        /// </summary>
        /// <param name="sender">his is the object which did fire the event</param>
        /// <param name="e">is an object to additional info</param>
		protected void DeleteAll_Click(object sender, EventArgs e)
		{
			if (GridViewInBox)
				MessageManager.DeleteAllReceivedMessagesByUser(user);
			else
				MessageManager.DeleteAllSentMessagesByUser(user);
			//Get List Messages           
			SetDataBind();
		}
        /// <summary>
        /// Event Handler 'button click' on the button 'reply'
        /// </summary>
        /// <param name="sender">his is the object which did fire the event</param>
        /// <param name="e">is an object to additional info</param>
		protected void LinkButtonReply_Click(object sender, EventArgs e)
		{
			Label_NickTitle.Text = LabelDest.Text;
			Label_Subj.Text = "Re: " + Label_Subj.Text;

			StringBuilder Quote = QuoteOriginalMEss();

			TextBoxViewTextPM.Text = Quote.ToString();

			TextBoxViewTextPM.ReadOnly = false;

			TextBoxViewTextPM.Focus();

			LinkButtonSendReply.Visible = true;
            LinkButtonReply.Visible = false;
            TextBoxViewTextPM.Visible = true;
            DivViewTextPM.Visible = false;

		}

		private StringBuilder QuoteOriginalMEss()
		{
			StringBuilder Quote = new StringBuilder(GetLocalResourceObject("HeaderReply").ToString());
			Quote.Append(Label_Nick.Text);
			Quote.Append("\r\n");
			Quote.Append(TextBoxViewTextPM.Text);
			Quote.Append("\r\n----------------------------------------\n\r\n");
			return Quote;
		}
        /// <summary>
        /// Event Handler 'button click' on the button 'send' after reply
        /// </summary>
        /// <param name="sender">his is the object which did fire the event</param>
        /// <param name="e">is an object to additional info</param>
		protected void LinkButtonSendReply_Click(object sender, EventArgs e)
		{

			Message sendMess = new Message { Title = Label_Subj.Text, Text = TextBoxViewTextPM.Text, Priority = false };
           	SendReport errorSend = sendMess.Send(user, Label_Nick.Text);
		//DivMessages.Visible = false;
			LinkButtonReply.Visible = true;
			//ReportSend(errorSend,false);
		}  
        /// <summary>
        /// Event Handler 'button click' on the button 'delete'
        /// </summary>
        /// <param name="sender">his is the object which did fire the event</param>
        /// <param name="e">is an object to additional info</param>
		protected void Delete_Click(object sender, EventArgs e)
		{

			for (int i = 0; i < GridViewMessages.Rows.Count; i++)
			{
				GridViewRow row = GridViewMessages.Rows[i];
				bool isChecked = ((CheckBox)row.FindControl("chkSelect")).Checked;

				if (isChecked)
				{

					int rowidx = GridViewMessages.PageSize * GridViewMessages.PageIndex;
					Message m = GridViewBox.ElementAt((rowidx) + i);
					m.Delete(user);
					
				
				}

			}          //Reset List Messages 
			SetDataBind();
        }
        #endregion
    }
}
